<?php


namespace app\socket\controller;


use app\common\model\DebugModel;
use app\common\model\MessageLogModel;
use app\common\services\RedisService;
use app\socket\services\BaseService;
use app\socket\services\LoginService;
use app\socket\services\ConnectService;
use app\socket\services\MessageService;
use app\socket\services\UserInfoService;
use GatewayWorker\Lib\Gateway;
use think\facade\Session;
use think\worker\Server;
use Workerman\Lib\Timer;
use \think\worker\Events as EventsBase;

class Events extends EventsBase
{
    protected static $ReDB;
    protected $name = 'ImService';


    /**
     * onWebSocketConnect 事件回调
     * 当客户端连接上gateway完成websocket握手时触发
     *
     * @param  integer  $client_id 断开连接的客户端client_id
     * @param  mixed    $data
     * @return void
     */
    public static function onWebSocketConnect($client_id, $data)
    {
//        dump(Session::get('ticket'));
//        var_export($data);
    }

    /**
     * 当客户端连接时触发
     * @param $client_id
     */
    public static function onConnect($client_id){
//        echo 'new user: '.$client_id . "\n";
        DebugModel::addInfo(0,'connect');
        //连接成果发送消息
        ConnectService::success(['type'=>'Access','client_id'=>$client_id]);
    }

    /**
     * 客户端发来消息时 触发
     * @param $client_id
     * @param $message
     *      type  pong 心跳返回
     */
    public static function onMessage($client_id,$message){
//        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:".json_encode($_SESSION)." onMessage:".$message."\n";


        $message_data = json_decode($message,true);


//        if($message_data['type']!='ping'){
//            echo " 新消息到达： session:".json_encode($_SESSION)." onMessage:".$message."\n";
//        }

        if(!$message_data)return ;
        //保存起来
        $_SESSION['client_id'] = $client_id;
        switch ($message_data['type']){
            //心跳返回
            case 'ping': return;
            //登录
            case 'login':
                LoginService::Login($message_data,$client_id);
                break;
            //客户端发言
            case 'say':
                if($message_data['to_user_id']){
                    BaseService::success($message_data,$message_data['to_user_id']);
                }
                break;
                //消息已读
            case 'is_reda':
                MessageService::upRedaMsg($message_data);
                break;
        }
    }



    /**
     * 守护进程时 启动 常驻内存
     * @param $businessWorker\
     */
    public static function onWorkerStart($businessWorker){
//        echo "1111111\n\n";
        // 调用Redis模型
//        $redis = RedisService::getInstance();
        if (RedisService::$status !== true) {
//            Exception('redis服务出错' . RedisService::$status);
        }
//        self::$ReDB = $redis;

        //只有id编号为0的进程上设置定时器 其他1,2,3,号进程不设置定时器
        if($businessWorker->id ===0){
            //定时器1  20 秒执行一次任务
            Timer::add(10,function(){
                //获取 当前的客服人数  以及  总连接数
//                $ClientCount = Gateway::getAllClientIdCount();
//                echo date('Y-m-d H:i:s')."---->>>>  当前在线人数：{$ClientCount}\n";
            });
        }

    }

    /**
     * 当客户端断开连接时
     * @param $client_id
     */
    public static function onClose($client_id){
        //debug
        echo " 连接断开： session:".json_encode($_SESSION)."  client_id:".$client_id."\n";
        //存在该信息  则 通知客服 该用户已经下线
        $userInfo = $_SESSION['userinfo'];

        //如果存在其他客户端 在线 则不提示离线
        if(count(Gateway::getClientIdByUid(BaseService::getUUid2()))>0){
            return;
        }

        //通知用户下线
        $msg_data = [
            'type'=>'offline',
            'id'=>$userInfo['id'],
            'role'=>$userInfo['role'],
        ];
        if($userInfo['role']==1){
            //客服下线 通知所有客服
            Gateway::sendToGroup(BaseService::$companyKey.$userInfo['admin_id'],json_encode($msg_data));
            // 通知客服房间中所有人
            Gateway::sendToGroup(BaseService::$roomKey.$userInfo['uuid'],json_encode($msg_data));
        }else{
            //顾客下线 通知所在的客服列表
            if(isset($userInfo['staff_id'])){
                BaseService::success($msg_data,$userInfo['staff_id']);
            }
            //通知顾客房间中的所有人  我离线了
//            Gateway::sendToGroup(BaseService::$roomKey.$userInfo['uuid'],json_encode($msg_data));
            BaseService::popOffLine($userInfo);
        }


    }

}